import { useCallback, useEffect } from "react";
import { useLocalStorage } from "@/hooks";

const CACHE_KEY = "_THEME_"; // 缓存Key
const mountDom = document.querySelector("html:root"); // 挂载节点

/**
 * 主题Hook
 *
 * @param {Object} initialValues 初始值
 * @returns
 */
const useTheme = (initialValues = {}) => {
  const [localValue, setLocalValue] = useLocalStorage(CACHE_KEY, {});

  // 属性挂载
  const onMount = useCallback((data) => {
    Object.entries(data).forEach(([key, value]) => (mountDom.dataset[key] = value));
  }, []);

  // 初始化值
  const initValues = useCallback(() => {
    const value = { ...initialValues, ...localValue };
    onMount(value);
    setLocalValue(value);
  }, [localValue, initialValues, setLocalValue, onMount]);

  useEffect(() => {
    if (mountDom.hasAttribute("data-loaded") === false) {
      initValues();
      mountDom.setAttribute("data-loaded", "");
    }
  }, [initValues]);

  // 更新值
  const onUpdateValue = useCallback(
    (data = {}) => {
      onMount(data);
      setLocalValue({ ...localValue, ...data });
    },
    [localValue, setLocalValue, onMount]
  );

  return [localValue, onUpdateValue];
};

export default useTheme;
